package com.lj.frame.config.redis;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Objects;


public class RedisKeySerialize implements RedisSerializer<String> {
    private String key;

    private final Charset charset;
    public static final StringRedisSerializer US_ASCII;
    public static final StringRedisSerializer ISO_8859_1;
    public static final StringRedisSerializer UTF_8;

    public RedisKeySerialize(String key) {
        this(StandardCharsets.UTF_8);
        this.key = key;
    }

    public RedisKeySerialize(Charset charset) {
        Assert.notNull(charset, "Charset must not be null!");
        this.charset = charset;
    }

    public String deserialize(@Nullable byte[] bytes) {
        if (Objects.isNull(bytes)){
            return null;
        }
        String result = new String(bytes, this.charset);
        if (result.startsWith(this.key)){
            return result.substring(this.key.length());
        }
        return result;
    }

    public byte[] serialize(@Nullable String string) {
        if (Objects.isNull(string)){
            return null;
        }
        return String.format("%s%s", this.key, string).getBytes(this.charset);
    }

    public Class<?> getTargetType() {
        return String.class;
    }

    static {
        US_ASCII = new StringRedisSerializer(StandardCharsets.US_ASCII);
        ISO_8859_1 = new StringRedisSerializer(StandardCharsets.ISO_8859_1);
        UTF_8 = new StringRedisSerializer(StandardCharsets.UTF_8);
    }
}
